package online.interceptor;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.logging.Logger;

/**
 * @Auther: 狼芒
 * @Date: 2021/9/1 23:38
 * @Descrintion: 拦截是否登录的请求
 * @version: 1.0
 * <p>
 * 登录检查
 * 1、配置好的拦截器拦截那些请求
 * 2、把这些配置放在容器中
 * 3、当心静态资源被拦截
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查逻辑
        HttpSession session = request.getSession();
        log.error("当前的路径是：{}", request.getRequestURI());
        Object user = session.getAttribute("user");
        System.out.println(user);
        //放行
        if (user == null) {
            return true;
        }
        //拦截,进行重定向
        session.setAttribute("msg", "login first");
        response.sendRedirect("/");

//        也可以进行转发
        request.setAttribute("msg", "login first");
        request.getRequestDispatcher("/").forward(request, response);
        return false;
    }

    /**
     * 目标方法执行完成以后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 目标方法渲染以后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
